package com.fandou.airobot.ui.recording;

import android.content.Context;
import android.media.Image;
import android.media.ImageReader;
import android.os.Environment;

import com.blankj.utilcode.util.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author Jm
 * @date 2020/7/8 14:28
 * @description
 */
public class JpegReaderListener implements ImageReader.OnImageAvailableListener {

    private Context mContext;

    private long timestamp;

    public JpegReaderListener(Context context, long timestamp) {
        this.mContext = context;
        this.timestamp = timestamp;
    }

    @Override
    public void onImageAvailable(ImageReader reader) {
        new Thread(new ImageSaver(reader)).start();
    }

    class ImageSaver implements Runnable {
        private ImageReader mImageReader;

        ImageSaver(ImageReader mImageReader) {
            this.mImageReader = mImageReader;
        }

        @Override
        public void run() {
            Image image = mImageReader.acquireLatestImage();
            checkParentDir();
            File file;
            checkJpegDir();
            file = createJpeg();
            try {
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                try {
                    save(bytes, file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.close();
            } catch (Exception e) {
                e.getStackTrace();
            }
        }
    }


    /**
     * 判断父文件是否存在
     */
    private void checkParentDir() {
        File dir = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/recording/");
        if (!dir.exists()) {
            dir.mkdir();
        }
    }

    /**
     * 判断文件夹是否存在
     */
    private void checkJpegDir() {
        File dir = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/recording/");
        if (!dir.exists()) {
            dir.mkdir();
        }
    }

    /**
     * 创建jpeg的文件
     *
     * @return
     */
    private File createJpeg() {
//        int random = new Random().nextInt(1000);
//        File externalFilesDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File dir = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/recording/");
        mIndex++;
        LogUtils.dTag("JpegSaver", "dir" + dir);
        return new File(dir, getFileName(timestamp));
    }

    /**
     * 标识图片的序号
     */
    private int mIndex = 0;

    private String getFileName(long timestamp) {
        return "record_" + timestamp + "_" + mIndex + ".jpg";
    }

    /***
     * 获取视频文件夹路径
     * @param context context
     * @return path
     */
    public static String getVideoFileName(Context context) {
        File dir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/recording/video/");
        if (!dir.exists()) {
            dir.mkdir();
        }
        return dir.getPath() + getVideoFileName();
    }

    private static String getVideoFileName() {
        return "record_video_" + System.currentTimeMillis() + ".mp4";
    }


    /**
     * 获取当前这次 记录的图片 list
     *
     * @return List<String>
     */
    public static List<String> getFileListByThisTime(Context context, long timestamp) {
        List<String> list = new ArrayList<>();
        File dir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/recording/");
        if (!dir.exists()) return null;
        if (dir.listFiles() != null && dir.listFiles().length > 0) {
            File[] files = dir.listFiles();
            assert files != null;
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File f1, File f2) {
                    return Long.compare(f1.lastModified(), f2.lastModified());
                }
            });

            for (File file : files) {
                if (file.getName().startsWith("record_" + timestamp)) {
                    list.add(file.getPath());
                    LogUtils.dTag("JpegSaver", "组装数据:" + file.getPath());
                }
            }
        }
        LogUtils.dTag("JpegSaver", "getFileListByThisTime:" + list.size());
        return list;
    }


    /**
     * 保存
     *
     * @param bytes bytes
     * @param file  file
     */
    private void save(byte[] bytes, File file) throws IOException {
        LogUtils.dTag("JpegSaver", "save");
        try (OutputStream os = new FileOutputStream(file)) {
            os.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
